﻿using Microsoft.EntityFrameworkCore;
using Questionnaire.Data.Models;
using System;
using System.Collections.Generic;
using System.Linq;

namespace Questionnaire.Server
{
    public class QuestionnaireServer
    {
        private QuestionnaireContext _dbContext;

        public QuestionnaireServer()
        {
            _dbContext = new QuestionnaireContext();
        }
        #region add
        public void CreateQuestionnaire(Data.Models.Questionnaire questionnaire)
        {
            if (CheckCreateQuestionnaire(questionnaire.Serial))
            {
                questionnaire.CreateTime = DateTime.Now;
                questionnaire.Serial = _dbContext.Questionnaire.Count() + 1;
                _dbContext.Questionnaire.Add(questionnaire);
                _dbContext.SaveChanges();
            }
            else
            {
                throw new Exception("问卷已存在！");
            }
        }

        public void CreateQuestion(Question question)
        {
            question.CreateTime = DateTime.Now;
            _dbContext.Question.Add(question);
            _dbContext.SaveChanges();
        }

        public void CreateOption(Option option)
        {           
            option.CreateTime = DateTime.Now;
            _dbContext.Option.Add(option);
            _dbContext.SaveChanges();
        }
        #endregion

        #region get
        public IEnumerable<Data.Models.Questionnaire> GetAllQuestionnaire(int userId)
        {
            var questionnaireList = _dbContext.Questionnaire.Where(q => q.UserId == userId && !q.IsDelete)
                .OrderBy(q =>q.Serial).ToList();
            return questionnaireList;
        }
        public Data.Models.Questionnaire GetQuestionnaireBySerial(int serial)
        {
            var questionnaire = _dbContext.Questionnaire.Include(qn => qn.Question).SingleOrDefault(qn => qn.Serial == serial && !qn.IsDelete);
            if (questionnaire == null)
                throw new Exception("找不到改问卷！");
            else
            return questionnaire;
        }
        public IEnumerable<Question> GetQuestionById(int questionnaireId)
        {
            var questionList = _dbContext.Question.Where(q => q.QuestionnaireId == questionnaireId && q.IsDelete.Equals(false))
                .OrderBy(q => q.Serial).ToList();
            return questionList;
        }

        public IEnumerable<Option> GetOptionById(int questionId)
        {
            var optionList = _dbContext.Option.Where(o => o.QuestionId == questionId && o.IsDelete.Equals(false))
                .OrderBy(q => q.Serial).ToList();
            return optionList;
        }


        #endregion

        #region update
        public void ModifyQuestionnaire(Data.Models.Questionnaire questionnaire)
        {
            var questionnaireResult = _dbContext.Questionnaire.Include(q=>q.Question).SingleOrDefault(q => q.QuestionnaireId == questionnaire.QuestionnaireId);
            questionnaireResult = questionnaire;
            _dbContext.SaveChanges();
        }

        public void ModifyQuestion(Question question)
        {
            var questionReault = _dbContext.Question.SingleOrDefault(q => q.QuestionId == question.QuestionId);
            questionReault = question;
            _dbContext.SaveChanges();
        }

        public void ModifyOption(Option option)
        {
            var optionResult = _dbContext.Option.SingleOrDefault(o => o.OptionId == option.OptionId);
            optionResult = option;
            _dbContext.SaveChanges();
        }
#endregion

        #region delete
        public void DeleteQuestionnaireById(int quesitonnaireId)
        {
            var questionnaire = _dbContext.Questionnaire.SingleOrDefault(q => q.QuestionnaireId == quesitonnaireId);
            if (questionnaire.IsDelete)
                throw new Exception("出现错误！");
            else
            {
                questionnaire.IsDelete = true;
                _dbContext.SaveChanges();
            }
           
        }
        public void DeleteQuestionById(int questionId)
        {
            var questionResult = _dbContext.Question.SingleOrDefault(q => q.QuestionId == questionId);
            if (questionResult.IsDelete)
                throw new Exception("出现错误！");
            else
            {
                questionResult.IsDelete = true;
                _dbContext.SaveChanges();
            }
            
        }

        public void DeleteOptionById(int optionId)
        {
            var optionResult = _dbContext.Option.SingleOrDefault(o => o.OptionId == optionId);
            if (optionResult.IsDelete)
                throw new Exception("出现错误！");
            else
            {
                optionResult.IsDelete = true;
                _dbContext.SaveChanges();
            }
           
        }

        #endregion
        #region check
        public bool CheckCreateQuestionnaire(int questionnaireSerail)
        {
            var questionnaire = _dbContext.Questionnaire.SingleOrDefault(q => q.Serial.Equals(questionnaireSerail));
            return questionnaire == null ? true : false;
        }
#endregion
        public void HangQuestionnaire(int qSerial,int userId)
        {
            var questionnaire = _dbContext.Questionnaire.SingleOrDefault(q => q.Serial == qSerial && q.UserId == userId && !q.IsDelete);
            if (questionnaire.IsHang)
                throw new Exception("问卷不能重复挂起！");
            else
            {
                questionnaire.IsHang = true;
                _dbContext.SaveChanges();
            }
           
        }
        public void RecordInvestigation(IEnumerable<Result> results)
        {
            if (results == null || results.Count() == 0)
            {
                throw new Exception("保存数据错误");
            }
            var ip = results.First().Ip;
            if (_dbContext.Result.Any(r => r.Ip == ip))
            {
                throw new Exception("同一ip不允许重复填卷");
            }
            foreach (var r in results)
            {
                AddOptionResult(r);//添加选项选择数
            }

            var questionnaire = _dbContext.Questionnaire.SingleOrDefault(qn =>qn.QuestionnaireId ==results.First().QuestionnaireId);
            questionnaire.FillNumber++;
            _dbContext.Result.AddRange(results);
            _dbContext.Tourist.Add(new Tourist()
            {
                Ip = ip,
                CommitTime = DateTime.Now,
                QuestionnaireId = results.First().QuestionnaireId,
            });

            _dbContext.SaveChanges();
        }

        public void AddOptionResult(Result r)
        {
            var questionnaire = _dbContext.Questionnaire.Include("Question")
                .Single(que => que.QuestionnaireId == r.QuestionnaireId);
            var question = questionnaire.Question.Single(qu => qu.Serial == r.QuestionSerial);
            var option = question.Option.Single(o => o.Serial == r.OptionSerial);
            option.SelectNumber++;
            _dbContext.SaveChanges();
        }
        /*  public int[,] GetQuestionnaireChartData(int userId, int serial)
          {
              var questionnaire = GetQuestionnaire(userId, serial);
              if (questionnaire == null)
              {
                  throw new Exception("get data fail!");
              }
              var count = questionnaire.Question.Max(q => q.Option.Count());//最大选项数
              int questions = questionnaire.Question.Count();//问题数
              int[,] data = new int[count, questions];
              List<Question> question = questionnaire.Question.Where(q => !q.IsDelete).ToList();
              for (int i = 0; i < questions; i++)
              {
                  var que = question.ElementAt(i);
                  for (int j = 0; j < count; j++)
                  {
                      if (que.Option.Count() > j)
                      {
                          data[j, i] = que.Option.ElementAt(j).SelectNumber;
                      }
                  }
              }
              return data;
          }*/
    }
}
